package work2;

public class Complex {
	public double Real;
	public double I;

	public Complex(double r, double i) {
		this.Real = r;
		this.I = i;
	}

	public static Complex Add(Complex a, Complex b) {
		Complex re = new Complex(0, 0);
		re.Real = a.Real + b.Real;
		re.I = a.I + b.I;
		return re;
	}

	public static Complex Sub(Complex a, Complex b) {
		Complex re = new Complex(0, 0);
		re.Real = a.Real - b.Real;
		re.I = a.I - b.I;
		return re;
	}

	public static Complex Mul(Complex a, Complex b) {
		Complex re = new Complex(0, 0);
		re.Real = a.Real * b.Real - a.I * b.I;
		re.I = a.I * b.Real + a.Real * b.I;
		return re;
	}

	public static Complex Div(Complex a, Complex b) {
		Complex re = new Complex(0, 0);
		re.Real = (a.Real * b.Real + a.I * b.I) / (b.Real * b.Real + b.I * b.I);
		re.I = (a.I * b.Real - a.Real * b.I) / (b.Real * b.Real + b.I * b.I);
		return re;
	}

	public String ToString() {
		String re = this.I >= 0
				? String.format("%.2f+%.2fi", this.Real, this.I)
				: String.format("%.2f%.2fi", this.Real, this.I);

		return re;
	}

	// int n: 保留 n 位小数
	public String ToString(int n) {
		String fmstr = "%." + Integer.toString(n) + "f";
		String re = this.I >= 0
				? String.format(fmstr + "+" + fmstr + "i", this.Real, this.I)
				: String.format(fmstr + "+" + fmstr + "i", this.Real, this.I);
		return re;
	}
}
